package pure.csw.activemq.topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import pure.csw.common.Constant;

import javax.jms.*;

public class TopicProduce {
    public static void main(String[] args) throws JMSException, InterruptedException {

        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(Constant.URL);
        Connection connection = factory.createConnection();
        connection.start();
        //开启一次会话，非事务，自动确认
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //创建消息
        TextMessage message = session.createTextMessage();
        //创建Topic Destination
        Topic topic = session.createTopic(Constant.TOPICNAME);
        //创建生产者
        MessageProducer producer = session.createProducer(topic);
        //创建消费者
        MessageConsumer consumer = session.createConsumer(topic);
        //设置消息监听器
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println(textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        message.setText("topic message");
        //生产者发送消息，非持久，优先度4，存活时间5s
        producer.send(message,DeliveryMode.NON_PERSISTENT, 4, 5000L);
        //等待消息发送和接受完毕
        Thread.sleep(5000);
        //关闭资源
        producer.close();
        consumer.close();
        session.close();
        connection.close();
    }
}
